#pragma once
#include <iostream>
#include <string>
#include <sys/types.h> /* See NOTES */
#include <sys/wait.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
#include <functional>   
#include <memory>

#include "Log.hpp"
#include "InterAddr.hpp"
#include "Socket.hpp"

using namespace socket_ns;
const static int defaultsockfd = -1;
const static int gbacklog = 16;

using http_t = std::function<std::string (std::string request)>;

enum
{
    SOCKET_ERROR = 1, 
    BIND_ERROR,
    USAGE_ERROR,
    LISTEN_ERROR
};

using namespace socket_ns;
class TcpServer;

class ThreadData
{
public:
    ThreadData(socket_sptr fd, InterAddr addr, TcpServer* s): sockfd(fd), clientaddr(addr), self(s)
    {

    }
public:
    socket_sptr sockfd;
    InterAddr clientaddr;
    TcpServer *self;
};

//using task_t = std::function<void()>;

class TcpServer
{
public:
    TcpServer(uint16_t port, http_t httpservice) 
        : _localaddr("0", port),
        _listensock(std::make_unique<TcpSocket>()),
        _http_service(httpservice),
        _isrunning(false)
    {
        std::cout << "BuidListenSocket" << std::endl;
        _listensock->BuidListenSocket(_localaddr);

    }

    static void* HanderSock(void *args)
    {
        pthread_detach(pthread_self());
        ThreadData *td = static_cast<ThreadData*>(args);

        // 这里虽然我们没有做判断是否读取完整的操作（粘报问题），但是有很大几率读取到完整的请求（测试)
        std::string request, response;
        ssize_t n = td->sockfd->Recv(&request); // 读取请求
        if (n > 0)
        {
            response = td->self->_http_service(request);
            td->sockfd->Send(response); // 应答：将读到的请求原封不动的发回去
        }
        td->sockfd->Close();
        delete td;
        return nullptr;
    }
    void Loop()
    {
        _isrunning = true;
        // 4. 不能直接接受数据， 先要获取连接
        while (_isrunning)
        {
            InterAddr peeraddr;
            //listensock只是用来监听的，具体的服务是accept返回的文件描述符来服务的。（服务员案例）
            socket_sptr normalsock = _listensock->Accpeter(&peeraddr);
            if (normalsock == nullptr)
            {
                continue;
            }
            //Version 2 采用多线程 //适合在长服务场景
            pthread_t t;
            ThreadData *td = new ThreadData(normalsock, peeraddr, this);
            pthread_create(&t, nullptr, HanderSock, td); // 将线程设置为分离状态
        }
        _isrunning = false;

    }
    ~TcpServer()
    {
    }

private:
    InterAddr _localaddr;
    std::unique_ptr<Socket> _listensock; 
    bool _isrunning;

    http_t _http_service;
};



